<template>
  <view class="preference-container">
    <!-- 使用普通view替代scroll-view -->
    <view class="job-list-container">
      <view class="job-card" v-for="(item, index) in jobList" :key="index" @tap="goToDetail(item)">
        <view class="job-header">
          <view class="job-title">{{item.jobName}}</view>
          <view class="job-salary">{{item.salary || '面议'}}</view>
        </view>
        <view class="job-company">{{item.companyName}}</view>
        <view class="job-info">
          <text class="job-tag job-address-tag" v-if="item.jobAddress">
            <text class="job-address-icon iconfont icon-location"></text>
            {{item.jobAddress}}
          </text>
          <text class="job-tag">{{getCompanyTypeText(item.companyType)}}</text>
          <text class="job-tag degree-tag">{{getDegreeText(item.degree)}}</text>
          <text class="job-tag" v-if="item.type !== undefined && item.type !== null && item.type !== ''">{{getTypeText(item.type)}}</text>
          <text class="job-tag" v-if="item.isWeave !== undefined && item.isWeave !== ''">{{getYesNoText(item.isWeave) === '是' ? '带编' : '不带编'}}</text>
        </view>
        <view class="job-status">
          <view class="job-application-time" v-if="item.startDate || item.endDate">
            <text class="job-time-label">报名时间：</text>
            <text class="job-time-value">{{ item.startDate && item.endDate ? `${item.startDate} ~ ${item.endDate}` : (item.endDate || '暂无') }}</text>
          </view>
          <text :class="['status-tag', getStatusClass(item.status)]">{{getStatusText(item.status)}}</text>
        </view>
      </view>
      
      <!-- 加载更多提示 -->
      <view class="loading-more" v-if="jobList.length > 0">
        <text v-if="isLoading">加载中...</text>
        <text v-else-if="!hasMore">没有更多数据了</text>
        <text v-else>加载更多中...</text>
      </view>
      
      <!-- 空状态提示 -->
      <view class="empty-state" v-if="jobList.length === 0 && !isLoading">
        <text class="empty-text">暂无相关职位</text>
      </view>
    </view>
  </view>
</template>

<script>
import { checkUserData, queryMatchJobList } from '@/api/recruitUserData/recruitUserData.js'
import { getDicts } from '@/api/dict/data'

export default {
  components: {
    uniLoadMore: () => import('@/uni_modules/uni-load-more/components/uni-load-more/uni-load-more.vue')
  },
  // 开启页面下拉刷新
  onPullDownRefresh: function() {
    return true;
  },
  // 设置页面属性
  // #ifdef MP
  enablePullDownRefresh: true,
  // #endif
  data() {
    return {
      statusBarHeight: 0,
      // 字典类型常量
      companyTypeDictType: 'recruit_company_type', // 企业类型字典
      degreeDictType: 'recruit_degree', // 学历字典
      typeDictType: 'recruit_type', // 招聘类型字典
      yesOrNoDictType: 'recruit_yes_no', // 是否字典
      // 字典数据
      companyTypeDict: [],
      degreeDict: [],
      typeDict: [],
      yesOrNoDict: [],
      jobList: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      isLoading: false,
      isRefreshing: false,
      hasMore: true,
      isDataComplete: false, // 标记用户资料是否完整
      // 加载更多状态
      loadMoreText: {
        contentdown: '上拉加载更多',
        contentrefresh: '加载中...',
        contentnomore: '没有更多数据了'
      },
      loadMoreTimer: null, // 用于防抖处理的定时器
    }
  },
  computed: {
    // 计算加载更多组件的状态
    loadMoreStatus() {
      if (this.isLoading) {
        return 'loading'
      } else if (!this.hasMore) {
        return 'noMore'
      } else {
        return 'more'
      }
    }
  },
  onLoad() {
    const systemInfo = uni.getSystemInfoSync();
    this.statusBarHeight = systemInfo.statusBarHeight;
    
    // 0.加载字典数据
    this.loadDictData()
    
    // 使用setTimeout延迟加载数据，避免页面初始化时卡顿
    setTimeout(() => {
      // 1.查询个人资料是否填写完整
      this.checkUserData()
      // 2.根据个人信息查询匹配岗位
      this.fetchJobList()
    }, 100);
  },
  
  // 监听页面触底事件
  onReachBottom() {
    console.log('页面触底事件触发');
    // 触底时加载更多
    if (!this.isLoading && this.hasMore) {
      this.loadMore();
    }
  },
  
  // 监听页面滚动
  onPageScroll(e) {
    // 当滚动到底部附近时自动加载更多
    const windowHeight = uni.getSystemInfoSync().windowHeight;
    const scrollTop = e.scrollTop;
    const documentHeight = this.jobList.length * 250; // 降低估算高度，提前触发加载
    
    // 提前触发加载更多，增加阈值
    if (documentHeight - scrollTop - windowHeight < 500 && !this.isLoading && this.hasMore) {
      this.loadMore();
    }
  },
  
  // 添加下拉刷新支持
  onPullDownRefresh() {
    console.log('触发下拉刷新');
    
    // 重置页码并刷新数据
    this.pageNum = 1;
    this.isRefreshing = true;
    
    // 先检查用户资料是否完整
    this.checkUserData().then(isComplete => {
      if (isComplete) {
        return this.fetchJobList(true);
      }
    }).finally(() => {
      this.isRefreshing = false;
      uni.stopPullDownRefresh(); // 停止下拉刷新动画
    });
  },
  
  // 页面显示时触发
  onShow() {
    // 重置滚动状态
    if (this.jobList.length > 0) {
      setTimeout(() => {
        uni.pageScrollTo({
          scrollTop: 0,
          duration: 0
        });
      }, 50);
    }
  },
  
  // 页面隐藏时触发
  onHide() {
    // 清除定时器
    if (this.loadMoreTimer) {
      clearTimeout(this.loadMoreTimer);
      this.loadMoreTimer = null;
    }
  },
  
  // 页面卸载时触发
  onUnload() {
    // 清除定时器
    if (this.loadMoreTimer) {
      clearTimeout(this.loadMoreTimer);
      this.loadMoreTimer = null;
    }
  },
  methods: {
    // 加载字典数据
    async loadDictData() {
      try {
        // 并行加载所有字典数据
        const [companyTypeRes, degreeRes, typeRes, yesOrNoRes] = await Promise.all([
          getDicts(this.companyTypeDictType),
          getDicts(this.degreeDictType),
          getDicts(this.typeDictType),
          getDicts(this.yesOrNoDictType)
        ]);
        
        // 处理企业类型字典
        if (companyTypeRes && companyTypeRes.code === 200) {
          this.companyTypeDict = companyTypeRes.data || [];
        }
        
        // 处理学历字典
        if (degreeRes && degreeRes.code === 200) {
          this.degreeDict = degreeRes.data || [];
        }
        
        // 处理招聘类型字典
        if (typeRes && typeRes.code === 200) {
          this.typeDict = typeRes.data || [];
        }
        
        // 处理是否字典
        if (yesOrNoRes && yesOrNoRes.code === 200) {
          this.yesOrNoDict = yesOrNoRes.data || [];
        }
      } catch (error) {
        console.error('加载字典数据失败', error);
        uni.showToast({
          title: '加载字典数据失败',
          icon: 'none'
        });
      }
    },
    
    // 查询个人资料是否填写完整
    async checkUserData() {
      try {
        const res = await checkUserData();
        
        if (res.code === 200) {
          this.isDataComplete = res.data;
          
          if (this.isDataComplete) {
            // 提示用户完善个人资料
            uni.showModal({
              title: '提示',
              content: '您的个人资料不完整，无法为您推荐匹配的岗位，是否前往完善资料？',
              confirmText: '去完善',
              cancelText: '暂不',
              success: (result) => {
                if (result.confirm) {
                  // 跳转到个人资料编辑页面
                  uni.navigateTo({
                    url: '/pagesA/mine/info/edit'
                  });
                }
              }
            });
          }
          
          return this.isDataComplete;
        } else {
          uni.showToast({
            title: res.msg || '获取用户资料状态失败',
            icon: 'none'
          });
          return false;
        }
      } catch (error) {
        console.error('检查用户资料完整性失败', error);
        uni.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none'
        });
        return false;
      }
    },

    // 获取职位列表
    async fetchJobList(isRefresh = false) {
      if (this.isLoading) return;
      
      this.isLoading = true;
      console.log('开始获取数据，页码:', this.pageNum, '每页数量:', this.pageSize);
      
      if (isRefresh) {
        this.pageNum = 1;
        this.jobList = [];
        this.hasMore = true;
      }
      
      try {
        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        };
        
        const res = await queryMatchJobList(params);
        console.log('API返回数据:', res);
        
        if (res.code === 200) {
          // 检查返回数据结构
          let rows = res.rows || res.data?.rows || [];
          let total = res.total || res.data?.total || 0;
          
          console.log('解析后数据:', {rows, total});
          
          if (isRefresh) {
            this.jobList = rows;
          } else {
            this.jobList = [...this.jobList, ...rows];
          }
          
          this.total = total;
          
          // 优化判断是否有更多数据的逻辑
          if (rows.length === 0 || rows.length < this.pageSize) {
            this.hasMore = false;
          } else {
            this.hasMore = this.jobList.length < total;
          }
          
          console.log('数据加载完成:', {
            当前数据量: this.jobList.length,
            总数据量: total,
            是否有更多: this.hasMore
          });
        } else {
          uni.showToast({
            title: res.msg || '获取数据失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('加载数据失败', error);
        uni.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none'
        });
      } finally {
        this.isLoading = false;
        this.isRefreshing = false;
      }
    },
    
    // 下拉刷新
    async onRefresh() {
      this.isRefreshing = true;
      
      // 先检查用户资料是否完整
      const isComplete = await this.checkUserData();
      if (isComplete) {
        await this.fetchJobList(true);
      } else {
        this.isRefreshing = false;
      }
    },
    
    // 新的刷新方法，使用按钮触发
    async handleRefresh() {
      if (this.isLoading || this.isRefreshing) return;
      
      uni.showLoading({
        title: '刷新中...',
        mask: true
      });
      
      this.isRefreshing = true;
      this.pageNum = 1;
      
      try {
        // 先检查用户资料是否完整
        const isComplete = await this.checkUserData();
        if (isComplete) {
          await this.fetchJobList(true);
        }
      } catch (error) {
        console.error('刷新失败', error);
      } finally {
        this.isRefreshing = false;
        uni.hideLoading();
        
        // 显示刷新成功提示
        uni.showToast({
          title: '刷新成功',
          icon: 'success',
          duration: 1500
        });
      }
    },
    
    // 加载更多
    loadMore() {
      console.log('触发loadMore', {hasMore: this.hasMore, isLoading: this.isLoading});
      
      if (!this.hasMore || this.isLoading) {
        console.log('不满足加载条件，退出');
        return;
      }
      
      this.pageNum++;
      console.log('页码增加到', this.pageNum);
      this.fetchJobList();
    },
    
    // 工具方法
    getCompanyTypeText(value) {
      if (value === undefined || value === null || value === '') return '不限';
      
      // 转换为字符串进行比较
      const strValue = String(value);
      if (this.companyTypeDict && this.companyTypeDict.length > 0) {
        const dictItem = this.companyTypeDict.find(item => String(item.dictValue) === strValue);
        if (dictItem) {
          return dictItem.dictLabel;
        }
      }
      
      // 硬编码映射，确保始终有值返回
      const companyTypeMap = {
        '0': '民企',
        '1': '央国企',
        '2': '事业单位',
        '3': '其他'
      };
      
      return companyTypeMap[strValue] || '不限';
    },
    
    getDegreeText(value) {
      if (value === undefined || value === null || value === '') return '不限';
      
      // 转换为字符串进行比较
      const strValue = String(value);
      if (this.degreeDict && this.degreeDict.length > 0) {
        const dictItem = this.degreeDict.find(item => String(item.dictValue) === strValue);
        if (dictItem) {
          return dictItem.dictLabel;
        }
      }
      
      // 硬编码映射，确保始终有值返回
      const degreeMap = {
        '1': '专科',
        '2': '本科',
        '3': '硕士研究生',
        '4': '博士研究生',
        '5': '其他'
      };
      
      return degreeMap[strValue] || '不限';
    },
    
    getTypeText(value) {
      if (value === undefined || value === null || value === '') return '不限';
      
      // 转换为字符串进行比较
      const strValue = String(value);
      if (this.typeDict && this.typeDict.length > 0) {
        const dictItem = this.typeDict.find(item => String(item.dictValue) === strValue);
        if (dictItem) {
          return dictItem.dictLabel;
        }
      }
      
      // 硬编码映射，确保始终有值返回
      const typeMap = {
        '1': '社会招聘',
        '2': '校园招聘'
      };
      
      return typeMap[strValue] || '不限';
    },
    
    getYesNoText(value) {
      if (value === undefined || value === null) return '不限';
      
      // 转换为字符串进行比较
      const strValue = String(value);
      if (this.yesOrNoDict && this.yesOrNoDict.length > 0) {
        const dictItem = this.yesOrNoDict.find(item => String(item.dictValue) === strValue);
        if (dictItem) {
          return dictItem.dictLabel;
        }
      }
      
      // 硬编码映射，确保始终有值返回
      return value == 1 || value == '1' ? '是' : value == 0 || value == '0' ? '否' : '不限';
    },
    
    getStatusText(value) {
      if (value === undefined || value === null || value === '') return '未知状态';
      
      // 硬编码映射，确保始终有值返回
      const statusMap = {
        3: '即将报名',
        1: '正在报名',
        2: '即将截止',
        4: '结束报名'
      };
      
      return statusMap[value] || '未知状态';
    },
    
    getStatusClass(value) {
      const classMap = {
        3: 'status-upcoming',    // 即将报名
        1: 'status-ongoing',     // 正在报名
        2: 'status-ending',      // 即将截止
        4: 'status-ended'        // 结束报名
      };
      return classMap[value] || '';
    },
    
    // 跳转到详情页
    goToDetail(item) {
      uni.navigateTo({
        url: `/pages/job/detail?jobId=${item.jobId}`
      });
    }
  }
}
</script>

<style lang="scss">
.preference-container {
  min-height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
  padding-top: 10rpx;
  box-sizing: border-box;
}

.job-list-container {
  flex: 1;
  padding: 10rpx 24rpx;
  box-sizing: border-box;
  width: 100%;
  padding-bottom: 100rpx;
}

.job-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  position: relative;
}

.job-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.job-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.job-salary {
  font-size: 32rpx;
  color: #ff7043;
  font-weight: bold;
}

.job-company {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 16rpx;
}

.job-info {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.job-tag {
  background: #f0f2f5;
  color: #666;
  font-size: 24rpx;
  padding: 6rpx 16rpx;
  border-radius: 6rpx;
}

.job-status {
  margin-top: 16rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 16rpx;
  border-top: 1rpx solid #f5f5f5;
}

.job-application-time {
  font-size: 24rpx;
  color: #666;
  display: flex;
}

.job-time-label {
  color: #999;
  margin-right: 4rpx;
}

.job-time-value {
  color: #666;
}

.status-tag {
  font-size: 24rpx;
  padding: 4rpx 16rpx;
  border-radius: 6rpx;
}

.job-address-tag {
  display: flex;
  align-items: center;
  background: #f0f2f5;
  color: #666;
  max-width: 95%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.job-address-icon {
  margin-right: 8rpx;
  font-size: 24rpx;
  color: #999;
  display: inline-flex;
}

.degree-tag {
  background-color: #e3f2fd;
  color: #1976d2;
}

.status-upcoming {
  background: #e3f2fd;
  color: #1976d2;
}

.status-ongoing {
  background: #e8f5e9;
  color: #2e7d32;
}

.status-ending {
  background: #fff3e0;
  color: #f57c00;
}

.status-ended {
  background: #f5f5f5;
  color: #757575;
}

.loading-more {
  text-align: center;
  padding: 20rpx 0;
  color: #999;
  font-size: 24rpx;
}

.loading-more text {
  display: inline-block;
  padding: 8rpx 20rpx;
  border-radius: 30rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}
</style> 